﻿using Oracle.ManagedDataAccess.Client;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XunChi.Log
{
    /// <summary>
    /// SQL语句日志帮助类。
    /// </summary>
    public class SqlLogHelper
    {
        /// <summary>
        /// 根据执行命令行打印SQL允许
        /// </summary>
        /// <param name="command"></param>
        public static void PrintSQL(DbCommand command)
        {
            if (command.Connection is OracleConnection)
            {
                command.CommandText = command.CommandText.Replace("@", ":");
            }
            string sql = command.CommandText;

            foreach (var parm in command.Parameters)
            {
                //parm是参数名字段
                string outPutParamValue = command.Parameters[$"{parm}"].Value.ToString();//参数值
                if (command.Connection is SqlConnection)
                {
                    sql = sql.Replace($"@{parm}", $"'{outPutParamValue}'");
                }
                else if (command.Connection is OracleConnection)
                {
                    sql = sql.Replace($":{parm}", $"'{outPutParamValue}'");
                }

                //获取对应的参数的值：
                //Console.WriteLine($"参数名=参数值是：{parm}={outPutParamValue}");//输出看看。
            }

            //Console.WriteLine($"重写LogCommand:记录将要执行的命令:{command.CommandText}");
            Console.WriteLine($"输出的SQL语句：\r\n{sql}{Environment.NewLine}");
        }
    }
}
